﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using QBZ.Evaluation.Models;
using System;
using System.Net;
using System.Threading.Tasks;

namespace QBZ.Evaluation.Views.Middleware
{

    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate next;

        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                var statusCode = context.Response.StatusCode;
                if (ex is ArgumentException)
                {
                    statusCode = 200;
                }
                await HandleExceptionAsync(context, statusCode);
            }
            finally
            {
                var statusCode = context.Response.StatusCode;
                if(statusCode != 200)
                {
                    await HandleExceptionAsync(context, statusCode);
                }
               
            }
        }

        private static Task HandleExceptionAsync(HttpContext context,int err)
        {
            var data = new ResponseModel(err);
            var result = JsonConvert.SerializeObject(data);
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(result);
        }
    }

    public static class ErrorHandlingExtensions
    {
        public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ErrorHandlingMiddleware>();
        }
    }
}
